#ifndef __ID_MANAGER_H__
#define __ID_MANAGER_H__


template<typename T>
struct IDNode
{
    bool bAvailable;    
    T *pObj;
};

template <typename T>
class IDManager
{
    public:
        IDManager(){
            m_nMaxNodeNum = -1;
        }

        ~IDManager(){
            m_nMaxNodeNum = -1;
            delete [] m_pIDNodes;
        }

        bool Init(unsigned short nMaxNodeNum){
            m_nMaxNodeNum = nMaxNodeNum;
            m_pIDNodes = new IDNode<T>[nMaxNodeNum];
            for(int i=0; i<nMaxNodeNum; i++){
                m_pIDNodes[i].pObj = NULL;
                m_pIDNodes[i].bAvailable = true;
            }
            return true;
        }

        bool Add(T* pObj){
            int i = 0;
            for(; i<m_nMaxNodeNum; i++){
                if (m_pIDNodes[i].bAvailable){
                    m_pIDNodes[i].bAvailable = false;
                    m_pIDNodes[i].pObj = pObj;
                    pObj->SetID(i);
                    break;
                }
            }

            if (i == m_nMaxNodeNum)
            {
                assert(false);
                return false;
            }
            return true;
        }

        bool Del(T* pObj){
            short nNodeID = pObj->GetID();
            if (nNodeID < 0 || nNodeID >= m_nMaxNodeNum)
                return false;

            if (m_pIDNodes[nNodeID].bAvailable)
                return false;

            pObj->SetID(-1);
            m_pIDNodes[nNodeID].bAvailable = true;
            m_pIDNodes[nNodeID].pObj = NULL;
            return true;
        }

        T* Get(short nNodeID){
            if (nNodeID < 0 || nNodeID >= m_nMaxNodeNum)
                return NULL;

            return m_pIDNodes[nNodeID].pObj;            
        }

    private:
        unsigned short m_nMaxNodeNum;
        IDNode<T>* m_pIDNodes;
};

#endif //__ID_MANAGER_H__
